//
//  MSCardView.m
//  navi_test
//
//  Created by alic on 2017/11/18.
//  Copyright © 2017年 msj. All rights reserved.
//

#import "ALCardView.h"


@interface ALCardViewCell : UIView

@property (assign, nonatomic) NSInteger maxHeight;
@property (assign, nonatomic) NSInteger minHeight;

@property (assign, nonatomic) CGFloat maxFontSize;
@property (assign, nonatomic) CGFloat minFontSize;

@property (assign, nonatomic) CGFloat factor;

@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) NSString *text;

@end

@implementation ALCardViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.minFontSize = 30.0;
        self.maxFontSize = 60.0;
        self.maxHeight = frame.size.height;
        self.minHeight = frame.size.height;
        self.backgroundColor = [UIColor clearColor];
        
        
        self.titleLabel = [[UILabel alloc]initWithFrame:self.bounds];
        self.titleLabel.font = [UIFont boldSystemFontOfSize:self.minFontSize];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:self.titleLabel];
        
    }
    
    return self;
}


-(void)setText:(NSString *)text
{
    _text = text;
    _titleLabel.text = text;
}


-(void)setFactor:(CGFloat)factor
{
    CGFloat width = self.frame.size.width;
    CGFloat height = self.minHeight + (self.maxHeight - self.minHeight) * factor;
    CGFloat  y = (self.maxHeight - height);
    CGFloat  x = self.frame.origin.x;
    self.frame = CGRectMake(x, y, width, height);
    
    CGFloat fontScale = self.minFontSize + (self.maxFontSize - self.minFontSize) * factor;
    fontScale = ceilf(fontScale);
    
    UIFont *font = [UIFont systemFontOfSize:fontScale];
    self.titleLabel.font = font;
    
    CGFloat labelHeight = self.titleLabel.font.capHeight + 4;
    CGFloat labelWidth = [self sizeWithString:self.text height:labelHeight font:font].width;
    CGRect labelFrame = CGRectMake((width-labelWidth)/2.0, height - labelHeight, labelWidth, labelHeight);
    self.titleLabel.frame = labelFrame;
    
}

-(CGSize)sizeWithString:(NSString *)string height:(CGFloat)h font:(UIFont *)font
{
    CGSize fSize = CGSizeMake(1000,h);
    CGSize size = [string boundingRectWithSize:fSize
                                options: NSStringDrawingTruncatesLastVisibleLine
            | NSStringDrawingUsesLineFragmentOrigin
            | NSStringDrawingUsesFontLeading
                             attributes:@{NSFontAttributeName:font}
                                context:nil].size;
    
    return size;
}

-(UIColor *)randomColor
{
    return [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1];
}

@end

@interface ALCardView ()<UIScrollViewDelegate>

@property (strong, nonatomic) UILabel *indicatorLabel;
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) NSMutableArray *arrM;

@property (assign, nonatomic) BOOL paddingFirst;
@property (assign, nonatomic) NSInteger displayCount;
@property (assign, nonatomic) NSInteger padding;
@property (assign, nonatomic) NSInteger itemWidth;

@end

@implementation ALCardView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {

        [self addSubviews];
        self.backgroundColor = [UIColor whiteColor];
        self.arrM = [NSMutableArray array];
        self.displayCount = 5;      // 默认要完整显示5个元素
        self.padding = -8.0;        // default
        self.itemWidth = 50.0;      // default
        self.paddingFirst = YES;    // paddingFirst = YES 保持padding不变,调整item宽度 paddingFirst = NO 保持itemWidth不变调整padding宽度
        
        self.scrollView.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)addSubviews {
    _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _scrollView.delegate = self;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = NO;
    _scrollView.alwaysBounceHorizontal = YES;
    _scrollView.clipsToBounds = NO;
    _scrollView.delegate = self;
    [self addSubview:_scrollView];
    
    _indicatorLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    _indicatorLabel.text = @"℃";
    _indicatorLabel.backgroundColor = [UIColor clearColor];
    [self addSubview:_indicatorLabel];
}

#pragma mark - Public
- (void)setCount:(NSInteger)count {
    if (count <= 0) {
        return;
    }
    
    [self.arrM makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.arrM removeAllObjects];
    
    // 如果想要显示5个元素，但是总共只有3个元素，那么就把三个元素都显示出来
    if (_displayCount > count) {
        _displayCount = count;
    }
    
    _count = count;
    
    CGFloat scrollW = self.scrollView.bounds.size.width;
    
    
    // 当需要调整默认的item宽度或者padding间距时，
    // paddingFirst = YES 保持padding不变,调整item宽度
    // paddingFirst = NO 保持itemWidth不变调整padding宽度
    BOOL paddingFirst = YES;
    
    // 按默认值计算出来的 元素 + 间距 总宽度小于scrollView的宽度，则需要调整padding或者itemWidth
    
    // paddingFirst = YES 保持padding不变,调整item宽度
    if (paddingFirst) {
        
        _itemWidth = (scrollW - _padding * (_displayCount + 1)) / _displayCount;
        
    }else{
        // paddingFirst = NO 保持itemWidth不变调整padding宽度
        _padding = (scrollW - _itemWidth * _displayCount) / (_displayCount + 1);
    }

    
    CGFloat calcW = _itemWidth * count + _padding * (count + 1);
    CGFloat contentSizeW = calcW > scrollW ? calcW : scrollW;
    self.scrollView.contentSize = CGSizeMake(contentSizeW, 0);
    
    CGFloat edgeInsetLeft  = scrollW/2.0 - (_padding + _itemWidth / 2.0);
    CGFloat edgeInsetRight  = scrollW/2.0 - (_padding + _itemWidth / 2.0);
    
    self.scrollView.contentInset = UIEdgeInsetsMake(0, edgeInsetLeft, 0, edgeInsetRight);

    /**
     0 padding
     1 padding + w + padding
     2 padding + w + padding + width + pading
     3 padding + w + padding + width + pading + width + pading
     */
    
    [self setCardViewCell];
    
    [self scrolling];
    [self endScroll:NO];
}

-(void)setCardViewCell
{
    for (int i = 0; i < _count; i++) {
        
        CGFloat scaleFactor = 0.4;

        CGFloat height = self.scrollView.bounds.size.height * scaleFactor;
        
        CGFloat x = _padding + i * (_itemWidth +  _padding);
        CGFloat y = (self.scrollView.bounds.size.height - height)/1.0;
        
        CGRect frame = CGRectMake(x, y, _itemWidth, height);
        
        ALCardViewCell *cell = [[ALCardViewCell alloc] initWithFrame:frame];
        cell.tag = i;
        cell.text = [NSString stringWithFormat:@"%d",i+10];
        cell.maxHeight = self.scrollView.bounds.size.height;
        cell.minHeight = height;
        [self.scrollView addSubview:cell];
        [self.arrM addObject:cell];
    }
    
}

-(void)scrolling{
    
    //屏幕中线
    CGFloat centerX = self.scrollView.contentOffset.x + self.scrollView.bounds.size.width/2.0f;
    
    //刷新cell缩放
    for (int i = 0;  i < self.arrM.count; i++) {
        
        ALCardViewCell *cell = self.arrM[i];
        
        CGFloat distance = fabs(cell.center.x - centerX);
        CGFloat factor = 0.0;
        
        //移动的距离和总距离的的比例
        if (distance < (_itemWidth + _padding)) {
            factor = 1.0 - distance/(_itemWidth + _padding);
        }
        cell.factor = factor;
    }
    
}
-(void)endScroll:(BOOL)animation{
    
    CGFloat offsetAdjustment = MAXFLOAT;
    CGFloat centerX = CGRectGetWidth(self.scrollView.bounds) / 2.0;
    CGFloat scrollCenterX = self.scrollView.contentOffset.x + centerX;

    ALCardViewCell *centerCell = nil;
    for (int i = 0;  i < self.arrM.count; i++) {
        
        ALCardViewCell *v = self.arrM[i];
        CGFloat itemCenterX = v.center.x;
        
        // 找出最小的offset 也就是最中间的item 偏移量
        if (ABS(itemCenterX - scrollCenterX) < ABS(offsetAdjustment)) {
            offsetAdjustment = itemCenterX - scrollCenterX;
            centerCell = v;
        }
    }
    
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x + offsetAdjustment, self.scrollView.contentOffset.y) animated:animation];
    
    
    if (centerCell) {
        
        CGRect frame = [self convertRect:centerCell.titleLabel.frame fromView:centerCell];
        self.indicatorLabel.center = CGPointMake(centerX + _itemWidth / 2.0, frame.origin.y);
        [self showTempIndicator];
        
    }
}

-(void)showTempIndicator
{
    //self.tempLabel.alpha = 0.0;
    self.indicatorLabel.hidden = NO;
    
//    [UIView animateWithDuration:0.5 animations:^{
//        self.tempLabel.alpha = 1.0;
//    }];
}
-(void)hiddenTempIndicator
{
    self.indicatorLabel.hidden = YES;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self scrolling];
}

// 开始滚动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self hiddenTempIndicator];
    
}
// 结束滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self endScroll:YES];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate) {
         [self endScroll:YES];
    }else{
        //[self showTempIndicator];
    }
}



#pragma mark - Rewrite
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if ([view isEqual:self]) {
        for (UIView *subview in self.arrM) {
            CGPoint offset = [self convertPoint:point toView:subview];
            if ((view = [subview hitTest:offset withEvent:event])) {
                return view;
            }
        }
        return self.scrollView;
    }
    return view;
}

@end
